package com.zdw.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.zdw.common.parent.JSONResult;
import com.zdw.demo.config.international.InternationalUtils;
import com.zdw.demo.config.zentao.ZenTaoConfig;
import com.zdw.demo.service.ZentaoUserService;
import com.zdw.demo.vo.ZentaoResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * (百搭)控制器
 * Controller : 控制器类
 * 用于对请求的内容、响应的内容进行数据格式转换。
 */
@Slf4j
@RestController
public class ZentaoController {

    @Autowired
    private ZentaoUserService service;

    @Autowired
    private ZenTaoConfig zenTaoConfig;

    /**
     * 生成禅道免登录的TOKEN、并初始化账号
     * 然后前端进行免密跳转：http://47.119.136.175:6060/api.php?m=user&f=apilogin&account=${用户账号}&code=${应用代码}&time=${时间戳}&token=${用户token}
     *
     * @param time
     * @param code
     * @param key
     * @return
     */
    @GetMapping(value = "/wportal/getTokenWithNoPassword", produces = "application/json")
    public JSONResult getTokenWithNoPassword(@RequestParam long time,
                                         @RequestParam String account,
                                         @RequestParam String realName,
                                         @RequestParam(defaultValue = "${ZenTaoConfig.code:kb}") String code,
                                         @RequestParam(defaultValue = "${ZenTaoConfig.key:bqkbolr26cu4bhl3a0w2vbo853l77hyx}") String key) {
        log.info("getTokenWithNoPassword, time:{}, code:{}, key:{}", time, code, key);
        // 1.加密获取TOKEN
        String md5Token  = service.generateMd5Token(code, key, time);
        String returnMsg = StrUtil.EMPTY;

        if (zenTaoConfig.isAutoCreateUser()) {
            // 2.用admin登录,获取admin的token,用于查询用户是否存在,不存在还需要根据admin的token创建用户
            String adminToken = service.getAdminToken();

            // 3.查询用户是否存在
            boolean isExist = service.checkUserExist(account);

            // 4.若用户不存在,则调用禅道API创建账号
            if (!isExist) {
                returnMsg = service.initZentaoAccount(account, realName, adminToken);
            }
        }

        // 5.返回免密登录数据，前端进行跳转：http://47.119.136.175:6060/api.php?m=user&f=apilogin&account=${用户账号}&code=${应用代码}&time=${时间戳}&token=${用户token}
        ZentaoResult zentaoResult = new ZentaoResult(time, md5Token, code, key, returnMsg);
        return new JSONResult().markSuccess(InternationalUtils.getInternational("common.success"), zentaoResult);
    }

}
